package com.hbnu.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSendDemo2 {
    public static void main(String[] args) {
        try {
            // 1、创建Socket
            DatagramSocket datagramSocket = new DatagramSocket(6666);

            // 2、准备需要通信的数据
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String content = null;
            while ((content = bufferedReader.readLine()) != null) {
                if ("bye".equalsIgnoreCase(content)) {
                    break;
                }
                DatagramPacket datagramPacket = new DatagramPacket(content.getBytes(), content.getBytes().length,
                        InetAddress.getByName("127.0.0.1"), 5555);
                // 3、发送数据
                datagramSocket.send(datagramPacket);
            }

            // 4、关闭Socket
            datagramSocket.close();  // 规范性代码中，网络资源的关闭是放到finally代码块中的
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
